/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.oktago.ibore;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Before showing the menu, the application looks for updates
 * @author massimo
 */
public class StartActivity extends Activity {

    public static final String VERSION = "Version";
    public static final int UPDATING_PROGRESS = 1;
    String[] versions;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        //getPreferences(MODE_PRIVATE).edit().putString(Const.APP_ID+"_"+VERSION, "").commit(); //uncomment this line if the version must be reset - for testing purposes only
        setContentView(R.layout.start);
        versions = new String[2];
        Boolean isOldVersion = null;
        try {
            isOldVersion = oldVersion(versions);
        } catch (IOException ex) {
            new AlertDialog.Builder(StartActivity.this).setMessage(R.string.CheckVersionError).setNeutralButton("Ok", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    StartActivity.this.finish();
                }
            }).show();
        }
        if (isOldVersion != null) {
            if (isOldVersion.booleanValue()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
                if (versions[0].equals("")) {
                    builder.setMessage("L'applicazione deve essere inizializzata. Continuare?");
                } else {
                    builder.setMessage("L'applicazione deve essere aggiornata. Continuare?");
                }
                builder.setCancelable(false).setPositiveButton("Si", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        try {
                            doUpdate();
                        } catch (IOException ex) {
                            Logger.getLogger(StartActivity.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        StartActivity.this.finish();
                    }
                }).show();
            } else {
                    Intent i = new Intent(StartActivity.this, DetailActivity.class);
                    Log.e("D", "Intent creato");
                    startActivity(i);
                    finish();
            }
        }
    }

    private void doUpdate() throws IOException {
        showDialog(UPDATING_PROGRESS);

        new Thread() {

            @Override
            public void run() {
                try {
                    IBoreApplication iBoreApplication=(IBoreApplication) StartActivity.this.getApplication();
                    iBoreApplication.updateIcons();
                    getPreferences(MODE_PRIVATE).edit().putString(Const.APP_ID+"_"+VERSION, versions[1]).commit();
                    Intent i = new Intent(StartActivity.this, DetailActivity.class);
                    Log.e("D", "Intent creato");
                    startActivity(i);
                    finish();
                } catch (Exception e) {
                    Log.e("E", "Errore");
                    Log.e("E", e.toString());
                }
            }
        }.start();
    }

    /**
     *
     * @param versions - array with two string which will be set with the current and online version
     * @return
     */
    private boolean oldVersion(String[] versions) throws IOException {
        versions[0] = getPreferences(MODE_PRIVATE).getString(Const.APP_ID+"_"+VERSION, "");
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL(Const.BASEPATH+Const.VERSION_URL).openStream()));
        String jSonOnlineVersion = in.readLine();
        in.close();
        try {
            versions[1] = new JSONObject(jSonOnlineVersion).getString("v");
        } catch (JSONException ex) {
            Logger.getLogger(StartActivity.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (!versions[0].equals(versions[1])) {
            return true;
        }
        return false;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == UPDATING_PROGRESS) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setTitle("Updating iBorè");
            dialog.setMessage("Please wait...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            return dialog;
        }
        return super.onCreateDialog(id);
    }
}
